package com.zyd.blog.homeart.service.impl;

import com.zyd.blog.homeart.service.ICommentReplyService;
import com.zyd.blog.homeart.util.TimeUtil;
import com.zyd.blog.persistence.beans.*;
import com.zyd.blog.persistence.mapper.CommentMapper;
import com.zyd.blog.persistence.mapper.CommentRelationMapper;
import com.zyd.blog.persistence.mapper.CommentReplyMapper;
import me.zhyd.oauth.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liusongqi
 * @since 2020-02-12
 */
@Service
public class CommentReplyServiceImpl  implements ICommentReplyService {
    @Autowired
    private CommentReplyMapper commentReplyMapper;
    @Autowired
    private TimeUtil timeUtil;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CommentRelationMapper commentRelationMapper;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public Integer addCommentReply(CommentReply commentReply) throws Exception {
        String uuid = UuidUtils.getUUID();
        commentReply.setDeleteState("1");
        commentReply.setReplyId(uuid);
        commentReply.setAddTime(sdf.format(System.currentTimeMillis()));
        commentReply.setUpdateTime(sdf.format(System.currentTimeMillis()));
        commentReply.setZanNumber(0);
        commentReply.setUseState("0");
        switch (commentReply.getUserId()) {
            case "1":
                commentReply.setUserName("用户名");
                commentReply.setUserImage("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2932779449,831692746&fm=26&gp=0.jpg");
                break;
            case "2":
                commentReply.setUserName("亚索");
                commentReply.setUserImage("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1652034236,78076834&fm=26&gp=0.jpg");
                break;
            case "3":
                commentReply.setUserName("卡牌大师");
                commentReply.setUserImage("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3940392874,3968870004&fm=26&gp=0.jpg");
                break;
            case "4":
                commentReply.setUserName("剑圣");
                commentReply.setUserImage("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=237035160,3996089600&fm=26&gp=0.jpg");
                break;
            case "5":
                commentReply.setUserName("李青");
                commentReply.setUserImage("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1051951030,907960917&fm=26&gp=0.jpg");
                break;
        }
        switch (commentReply.getReplyuserId()) {
            case "1":
                commentReply.setReplyuserName("用户名");
                commentReply.setReplyuserImage("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2932779449,831692746&fm=26&gp=0.jpg");
                break;
            case "2":
                commentReply.setReplyuserName("亚索");
                commentReply.setReplyuserImage("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1652034236,78076834&fm=26&gp=0.jpg");
                break;
            case "3":
                commentReply.setReplyuserName("卡牌大师");
                commentReply.setReplyuserImage("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3940392874,3968870004&fm=26&gp=0.jpg");
                break;
            case "4":
                commentReply.setReplyuserName("剑圣");
                commentReply.setReplyuserImage("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=237035160,3996089600&fm=26&gp=0.jpg");
                break;
            case "5":
                commentReply.setReplyuserName("李青");
                commentReply.setReplyuserImage("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1051951030,907960917&fm=26&gp=0.jpg");
                break;
        }
        int insert;
        try {
            insert = commentReplyMapper.insert(commentReply);
        } catch (Exception e) {
            throw new Exception("添加评论回复失败");
        }
        try {
            commentMapper.countComment(commentReply.getCommentId());
        } catch (Exception e) {
            throw new Exception("评论数量+1失败");
        }
        CommentRelation commentRelation = new CommentRelation();
        Integer integer =  commentRelationMapper.commentCount(commentReply.getReplyId(), commentReply.getUserId());
        if (integer == 0) {
            try {
                commentRelation.setId(uuid);
                commentRelation.setZan("1");
                commentRelation.setDiscuss("0");
                commentRelation.setUserId(commentReply.getUserId());
                commentRelationMapper.insert(commentRelation);
            } catch (Exception e) {
                throw new Exception("添加commentRelation失败");
            }
        } else if (integer == 1) {
            try {
                commentRelationMapper.commentUpdate(commentReply.getReplyId(), commentReply.getUserId());
            } catch (Exception e) {
                throw new Exception("修改commentRelation失败");
            }
        }
        return insert;
    }

    @Override
    public Map<String, Object> Reply(String commentId, String state,String userId) throws Exception {
        CommentNew commentNew;
        try {
            commentNew = commentMapper.Reply(commentId, state,userId);
        } catch (Exception e) {
            throw new Exception("获取评论失败");
        }
        Map<String,Object> map = new HashMap<>();
        String addTime1 = commentNew.getAddTime();
        commentNew.setAddTime(time(addTime1));
        map.put("commentNew",commentNew);
        List<CommentReplyNew> reply;
//        try {
            reply = commentReplyMapper.Reply(commentId, state, userId);
//        } catch (Exception e) {
//            throw new Exception("根据评论id获取评论回复失败");
//        }
        if (reply.size()>0){
            for (CommentReplyNew comment : reply) {
                String addTime = comment.getAddTime();
                comment.setAddTime(time(addTime));
                map.put("comment",reply);
            }
        }else {
            map.put("comment",new ArrayList<>());
        }

        CommentReply commentReply = new CommentReply();
        commentReply.setCommentId(commentId);

        int i;
        try {
            i = commentReplyMapper.selectCount(commentReply);
        } catch (Exception e) {
            throw new Exception("获取评论回复数量失败");
        }
        map.put("count",i);
        return map;
    }

    @Override
    public Integer deleteCommentReply(String commentId,String replyId, String userId) throws Exception {
        List<CommentReply> pid = commentReplyMapper.pid(commentId);
        Map<String,String> map = new HashMap<>();
        for (CommentReply id : pid) {
            map.put(id.getReplyId(), id.getPid());
        }
        System.out.println("—— —— —— —— —— ——原始的Map —— —— —— —— —— —— ——");

        Set<String> keys=map.keySet();
        Iterator<String> iterator=keys.iterator();
        System.out.println("ID —— PID");
        while(iterator.hasNext()){
            String i=iterator.next();
            System.out.println(i+"  —— "+map.get(i));
        }

        //递归删除k的所有子节点
        System.out.println("—— —— —— —— —— ——删除掉的节点 —— —— —— —— —— —— ——");
        removeTreeNodes(map,replyId,commentId);
        //删除k节点本身
        map.remove(replyId);
        try {
            commentMapper.jianComment(commentId);
        } catch (Exception e) {
            throw new Exception("评论数量-1失败！");
        }
        commentReplyMapper.deleteCommentReply(replyId);
        System.out.println();
        System.out.println("—— —— —— —— —— —— 递归删除["+replyId+"]的所有子节点后的Map —— —— ");

        iterator=keys.iterator();
        System.out.println("ID —— PID");
        while(iterator.hasNext()){
            String i=iterator.next();
            //;
            System.out.println(i+"  —— "+map.get(i));
        }
        return null;
    }
    //递归删除所有的子节点
    public  void removeTreeNodes(Map<String, String> t, String k,String commentId) throws Exception {
        //所有需要删除的子节点
        List<String> sons=new ArrayList<String>();
        sons.add(k);
        List<String> temp=new ArrayList<String>();
        //循环递归删除，所有以k为父节点的节点
        while(true){
            for(String s:sons){
                Set<String> keys=t.keySet();
                Iterator<String> it=keys.iterator();
                while(it.hasNext()){

                    String n=it.next();
                    //如果父节点（即Map的value）为需要删除的节点，则记录此节点，并在Map中删除
                    if(t.get(n).equals(s)){

                        temp.add(n);
                        it.remove();
                        try {
                            commentMapper.jianComment(commentId);
                        } catch (Exception e) {
                            throw new Exception("评论数量-1失败！");
                        }
                        commentReplyMapper.deleteCommentReply(n);

                        System.out.println("删除了ID=["+n+"]的节点,其父节点为["+s+"]");
                    }
                }
            }
            //如果此节点包含子节点，则将子节点赋值给sons;否则表示所有子节点已经删除，结束循环
            if(temp.size()>0){
                sons=temp;
                temp=new CopyOnWriteArrayList<String>();
            }else{
                break;
            }
        }
    }

    private String time(String date) throws ParseException {
        int day1 = timeUtil.day(date);
        if (day1 == 0) {
            int minute = timeUtil.minute(date);
            if (minute == 0) {
                return "刚刚";
            } else if (minute > 0 & minute < 60) {
                return minute + "分钟以前";
            } else if (minute >= 60 & minute < 1440) {
                return minute / 60 + "小时以前";
            }
        } else if (day1 == -1) {
            return "昨天" + date.substring(11, 16);
        } else if (day1 == -2) {
            return"前天" + date.substring(11, 16);
        }
        return date.substring(0, 16);
    }
}
